# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: jhkim

from coin.strategy.mm.base.feed_arb_base import (FeedArbSubscriberHandler, FeedArbSubsystem)

from coin.exchange.bitmex.ws.subscriber import BitmexSubscriber
from coin.strategy.mm.feed_arb import BitmexFeedArbFlowBookBuilder
from coin.strategy.mm.subscription import SubscriptionRequest


class BitmexFeedArbSubscriberHandler(FeedArbSubscriberHandler):
  SubscriberType = BitmexSubscriber

  def init_subscriber(self):
    if self._subscriber is not None:
      self._subscriber.stop()
      self._logger.info('Restarting %s subscriber...' % self._worker_id)

    sub_list = []
    for native_symbol in self._native_symbols:
      sub_list += [
          'orderBookL2:%s' % native_symbol,
          'trade:%s' % native_symbol,
          'instrument:%s' % native_symbol,
          'liquidation:%s' % native_symbol
      ]
    subscription_str = ','.join(sub_list)
    self._subscriber = BitmexSubscriber(self._queue,
                                        'a',
                                        self._worker_id,
                                        subscription=subscription_str,
                                        close_callback=self._on_disconnect)
    self._subscriber.start(self._ioloop)
    self._available = True


class BitmexFeedArbSubsystem(FeedArbSubsystem):
  FlowBookBuilder = BitmexFeedArbFlowBookBuilder
  FeedSubscriber = BitmexFeedArbSubscriberHandler
  FeedSubReq = SubscriptionRequest('Futures', 'Bitmex', None)
